import requests
import threading
import flask
import socket
import flask_cors
import time

app = flask.Flask(__name__)
flask_cors.CORS(app)
PORT = 6000


def discover_server(timeout=10):
    """自动发现服务器"""
    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.settimeout(timeout)
    
    # 绑定到广播端口
    sock.bind(('', 37020))
    
    print("正在搜索服务器...")
    start_time = time.time()
    
    while time.time() - start_time < timeout:
        try:
            data, addr = sock.recvfrom(1024)
            if data.startswith(b'MUSIC_SERVER:'):
                _, port = data.decode().split(':')
                return (addr[0], int(port))
        except socket.timeout:
            continue
        except Exception as e:
            print(f"发现错误: {str(e)}")
    
    return None

SERVER_URL = ''

def search_song():
    query = input("请输入歌曲名或歌手：")
    response = requests.get(f'{SERVER_URL}/search?q={query}')
    results = response.json()
    for idx, song in enumerate(results):
        print(f"{idx+1}. {song['title']} - {song['artist']}")
    choice = input("选择要添加的歌曲序号（回车取消）：")
    if choice.isdigit():
        index = int(choice) - 1
        if 0 <= index < len(results):
            requests.post(f'{SERVER_URL}/add_song', json=results[index])

def add_local():
    path = input("请输入本地文件路径：")
    requests.post(f'{SERVER_URL}/add_song_from_client', json={'type': 'local', 'path': path})

def add_url():
    url = input("请输入歌曲URL：")
    requests.post(f'{SERVER_URL}/add_song_from_client', json={'type': 'url', 'url': url})

def control_playback():
    print("\n1. 强制开始播放")
    print("2. 强制停止播放")
    choice = input("请选择操作：")
    command = 'start' if choice == '1' else 'stop'
    response = requests.post(
        f'{SERVER_URL}/playback_control',
        json={'command': command}
    )
    print(response.json()['status'])

def show_queue():
    try:
        response = requests.get(f'{SERVER_URL}/get_queue', timeout=5)
        queue = response.json()
        if not queue:
            print("\n当前播放列表为空")
            return

        print("\n当前播放列表：")
        print("-" * 60)
        for idx, song in enumerate(queue, 1):
            print(f"{idx}. [{song['type'].upper()}] {song['title']} - {song['artist']}")
            if song['type'] == 'local':
                print(f"   文件：{song.get('path', '未知路径')}")
            else:
                print(f"   链接：{song.get('url', '未知链接')}")
            print("-" * 60)
    except requests.exceptions.Timeout:
        print("获取列表超时，请检查服务器状态")
    except requests.exceptions.ConnectionError:
        print("无法连接到服务器")
    except Exception as e:
        print(f"发生错误：{str(e)}")

@app.route('/add_song_from_web', methods=['POST'])
def add_song():
    print('=================')
    data = flask.request.json
    print(data)
    response = requests.post(f'{SERVER_URL}/add_song_from_client',
                                json=data, timeout=5)
    if response.json()['status'] != 'success':
        return flask.jsonify({'status': 'failed'})
    return flask.jsonify({'status': 'success'})

def main():
    while True:
        print("\n1. 搜索并添加歌曲(不可用)")
        print("2. 添加本地歌曲(非主机不可用)")
        print("3. 添加URL")
        print("4. 播放控制")
        print("5. 查看播放列表")
        print("6. 退出")
        choice = input("请选择操作：")
        if choice == '1':
            search_song()
        elif choice == '2':
            add_local()
        elif choice == '3':
            add_url()
        elif choice == '4':
            control_playback()
        elif choice == '5':
            show_queue()
        elif choice == '6':
            break

@app.route('/')
def index():
    return "Music Server"

if __name__ == '__main__':
    server = discover_server()
    if server:
        print(f"找到服务器: {server[0]}:{server[1]}")
        SERVER_URL = f'http://{server[0]}:{server[1]}'
    else:
        SERVER_URL = input("SERVER IP:")
        print("未找到可用服务器")

    threading.Thread(target=main,daemon=True).start()
    app.run(host='0.0.0.0', port=PORT)
